/*
 * @ModuleName:
 * @Author: zhuzhaofeng
 * @Date: 2020-05-08 21:10:26
 */
import axios from "axios";
// Full config:  https://github.com/axios/axios#request-config
let config = {
  baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
  timeout: 60 * 1000,
  withCredentials: true,
};
const instance = axios.create(config);

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
);

// 添加响应拦截器
instance.interceptors.response.use(
  (res) => res.data,
  (error) => Promise.reject(error.message)
);

export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params,
      })
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

export const post = async (url, params = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params)
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

export const del = async (url, params = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .delete(url, {
        params,
      })
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

export const put = async (url, params = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .put(url, params, config)
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

/**
 * postFormData方法，对应post请求，用来提交文件+数据
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export const postFormData = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      headers: {
        "Content-Type": "multipart/form-data",
      },
      transformRequest: [
        function(data) {
          // 在请求之前对data传参进行格式转换
          const formData = new FormData();
          Object.keys(data).forEach((key) => {
            formData.append(key, data[key]);
          });
          return formData;
        },
      ],
      url: `${process.env.VUE_APP_BASE_API}${url}`,
      method: "post",
      data: params,
    })
      .then((res) => resolve(res.data))
      .catch((err) => reject(err.message));
  });
};
